package com.birdboot.core;

import com.birdboot.annotations.Controller;
import com.birdboot.annotations.RequestMapping;
import com.birdboot.controller.UserController;
import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 *
 * */
public class DispatcherServlet {
    //单例模式
    private static DispatcherServlet instance = new DispatcherServlet();
    private DispatcherServlet(){}
    public static DispatcherServlet getInstance(){return instance;}
    private static File baseDir;
    private static File staticDir;
    static {
        try {
            baseDir = new File(DispatcherServlet.class.getClassLoader().getResource(".").toURI());
            staticDir = new File(baseDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public void service(HttpServletRequest request, HttpServletResponse response)  {
        String path = request.getRequestURI();
        System.out.println("抽象路径"+path);
        Method method = HandlerMapping.getMapping(path);
        if(method != null){
            Class cls = method.getDeclaringClass();
            try {
                Object obj = cls.newInstance();
                method.invoke(obj,request,response);
            }catch ( IllegalArgumentException | ReflectiveOperationException e){
                e.printStackTrace();
            }


        }else {
        File file = new File(staticDir,path);
        if(!file.isFile()){
            file = new File(staticDir,"404.html");
            response.setStatusCode(404);
            response.setStatusReason("Not Found");
            response.addHeader("Server","BirdServer");
        }else {
            response.addHeader("Server","BirdServer");
        }
        response.setContentFile(file);
        }
    }
}
